// Construct world population, world gdp per capita and population gdppc growth rates across different periods

*houskeeping
clear
clear matrix
set mem 3000m
set more off
args base 



//local base "/Users/rls7/Library/CloudStorage/Dropbox/Shared_Projects/Long run beta/Writeup/5_JPE Macro_R2_final/Code/"

//----------------------------------------------
//----------------------------------------------
//----------------------------------------------
//----------------------------------------------
//Interpolate Maddison population data



insheet using "$base/InputData/maddison.csv", clear
keep y gdptotal poptotal
rename y year
tsset year
tsfill
ipolate pop year, gen(pop2)
replace pop2=pop2
ipolate gdp year, gen(gdp2)
replace gdp2=gdp2


keep year pop2 gdp2
rename pop2 pop
rename gdp2 gdp
gen gdppc=gdp/(1000*pop)
drop if year==2009
//outsheet year pop using "`base'/Outputs/Data/maddison_popgdp.csv", comma replace
//clear
drop if year<1275
gen temp=mod(year,25)
keep if temp==0
drop temp


gen temp = gdppc if year == 1800
egen norm_factor=min(temp)
gen gdppc_norm = gdppc / norm_factor
drop norm_factor temp




outsheet year gdppc gdppc_norm pop if year>1275 using "$base/Outputs/Data/popgdppcIndex.csv", comma replace




* Function to calculate and create a variable for compounded annual growth rate (CAGR)
capture program drop cagr
program define cagr
    args varname start end
    qui su `varname' if year == `start'
    local start_val = r(mean)
    qui su `varname' if year == `end'
    local end_val = r(mean)
    local cagr = ((`end_val' / `start_val') ^ (25 / (`end' - `start'))) 
    replace cagr_`varname' = `cagr' if year == `end'
end

gen cagr_pop = .
gen cagr_gdppc = .

cagr gdppc 1275 1775
cagr gdppc 1775 1875
cagr gdppc 1875 2000


cagr pop 1275 1700
cagr pop 1700 1875
cagr pop 1875 2000



keep if cagr_pop!=. | cagr_gdppc!=. | year==1275
drop pop gdp gdppc
rename cagr* gr*


outsheet year gr_pop gr_gdppc using "$base/Outputs/Data/grPopGdppc.csv", comma replace

